#!groovy

@Library('jenkinslibrary@master') _

//func from shareibrary
def build = new org.devops.build()
//def deploy = new org.devops.deploy()
def tools = new org.devops.tools()
def gitlab = new org.devops.gitlab()
def sonar = new org.devops.sonarqube()
def sonarapi = new org.devops.sonarapi()
def k8s = new org.devops.kubernetes()

def runOpts
//env
String buildType = "${env.buildType}"
String buildShell = "${env.buildShell}"
String deployHosts = "${env.deployHosts}"
String srcUrl = "${env.srcUrl}"
String branchName = "${env.branchName}"
String serviceName = "${env.serviceName}"

String dockerFile = "${env.dockerFile}"



//pipeline
pipeline{
    agent { node { label "master"}}
    
    
    stages{

        stage("CheckOut"){
            steps{
                script{
                   
                    
                    println("${branchName}")
                
                    tools.PrintMes("获取代码","green")
                    checkout([$class: 'GitSCM', branches: [[name: "${branchName}"]], 
                                      doGenerateSubmoduleConfigurations: false, 
                                      extensions: [], 
                                      submoduleCfg: [], 
                                      userRemoteConfigs: [[credentialsId: 'git', url: "${srcUrl}"]]])

                }
            }
        }
        stage("Build"){
            steps{
                script{
                
                    tools.PrintMes("执行打包","green")
                    build.Build(buildType,buildShell)
                    //artifactory.main(buildType,buildShell)
                    //artifactory.PushArtifact()
                    
                    //上传制品
                    //nexus.main("nexus")
                    
                    //发布制品
                    //sh " wget ${artifactUrl} && ls "
                    
                    
                    


                    //deploy.SaltDeploy("${deployHosts}","test.ping")
                    //deploy.AnsibleDeploy("${deployHosts}","-m ping ")
                }
            }
       }
       
    //并行
        stage('parallel01') {
       
         
          parallel {
            
            /*
            stage("QA"){
                steps {
                    script{
                        tools.PrintMes("搜索项目","green")
                        result = sonarapi.SerarchProject("${JOB_NAME}")
                        println(result)
                        
                        if (result == "false"){
                            println("${JOB_NAME}---项目不存在,准备创建项目---> ${JOB_NAME}！")
                            sonarapi.CreateProject("${JOB_NAME}")
                        } else {
                            println("${JOB_NAME}---项目已存在！")
                        }
                        
                        tools.PrintMes("配置项目质量规则","green")
                        qpName="${JOB_NAME}".split("-")[0]   //Sonar%20way
                        sonarapi.ConfigQualityProfiles("${JOB_NAME}","java",qpName)
                    
                        tools.PrintMes("配置质量阈","green")
                        sonarapi.ConfigQualityGates("${JOB_NAME}",qpName)
                    
                        tools.PrintMes("代码扫描","green")
                        sonar.SonarScan("test","${JOB_NAME}","${JOB_NAME}","src","${branchName}")
                        
    
                        sleep 30
                        tools.PrintMes("获取扫描结果","green")
                        result = sonarapi.GetProjectStatus("${JOB_NAME}")
                        
                        
                        println(result)
                        if (result.toString() == "ERROR"){
                            toemail.Email("代码质量阈错误！请及时修复！",userEmail)
                            error " 代码质量阈错误！请及时修复！"
                            
                            
                        } else {
                            println(result)
                        }
                    }
               }
           }
           */
           
    //构建镜像
        
        stage("BuildImages"){
            steps{
                script{
                    tools.PrintMes("构建上传镜像","green")
                    serviceName = "${JOB_NAME}".split("_")[1]
                    
                    tools.PrintMes("构建名称serviceName",serviceName)
                       
                    withCredentials([usernamePassword(credentialsId: 'aliyun-registry-admin', passwordVariable: 'password', usernameVariable: 'username')]) {
                           
                        env.dockerImage = "harbor.uda-edu.com/sunschool/${serviceName}:${branchName}"
                        sh """
                            docker login -u ${username} -p ${password}  harbor.uda-edu.com
                            docker build -f ${dockerFile} -t harbor.uda-edu.com/sunschool/${serviceName}:${branchName} .
                            sleep 1
                            docker push harbor.uda-edu.com/sunschool/${serviceName}:${branchName}
                            sleep 1
                            #docker rmi harbor.uda-edu.com/sunschool/${serviceName}:${branchName}
                            """
                    }
                }
            }
        }
    }
}
        
        /*
        stage("BuildJar"){
            steps{
                script{
                    tools.PrintMes("构建上传jar","green")
                   
                       
                    sshPublisher(publishers: [sshPublisherDesc(configName: 'uat-sunx', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: '''/usr/local/${JOB_NAME}/stop.sh
/usr/local/${JOB_NAME}/replace.sh
/usr/local/${JOB_NAME}/startup.sh''', execTimeout: 120000, flatten: true, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '', remoteDirectorySDF: false, removePrefix: '', sourceFiles: '${serviceName}')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
               }
            }
        }
        */
        
        //发布
        
        stage("Deploy"){
            steps{
                script{
                    tools.PrintMes("发布应用","green")
                    serviceName = "${JOB_NAME}".split("_")[1]
                    
                    tools.PrintMes("构建名称serviceName",serviceName)
                    
                    println(serviceName)
                    
                    //releaseVersion = "${branchName}".split("-")[-1]
                    response = gitlab.GetRepoFile(40,"uat-${serviceName}.yaml")
                    println(response)
                    
                    //发布kubernetes
                    k8s.UpdateDeployment("sunx-uat","${serviceName}",response)
                    

                }
            }
        }
        
        
        stage("Rollout"){
            steps{
                script{
                    tools.PrintMes("滚动更新pods","green")
                   
                       
                    sshPublisher(publishers: [sshPublisherDesc(configName: 'prod-sunx', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: '''/data/uat-rollout/${JOB_NAME}/restart.sh''', execTimeout: 120000, flatten: true, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '', remoteDirectorySDF: false, removePrefix: '', sourceFiles: '${serviceName}')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
               }
            }
        }
        
       
    }
    
}
